﻿using MyMusicPlayer.Domain;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyMusicPlayer.Utils
{
    /// <summary>
    /// 解析音频文件，获取相关信息的工具类
    /// </summary>
    class AudioFileHelper
    {
        static List<FileInfo> FileList = new List<FileInfo>();
        /// <summary>
        /// 根据音频文件的全路径，获取该文件的元数据，实例化返回MusicInfo对象
        /// </summary>
        /// <param name="fullPath"></param>
        /// <returns></returns>
        public static MusicInfo GetMusicInfoByFileFullPath(string fullPath)
        {
            TagLib.File tagFile = TagLib.File.Create(fullPath);
            MusicInfo musicInfo = new MusicInfo()
            {
                Name = tagFile.Tag.Title,
                Album = tagFile.Tag.Album,
                Artist = tagFile.Tag.FirstArtist,
                Duration = (int)tagFile.Properties.Duration.TotalSeconds,
            };

            // 设置歌曲文件的其他属性
            string str = musicInfo.Name + musicInfo.Artist + musicInfo.Album + musicInfo.Duration;
            musicInfo.Id = MD5Helper.CreateMD5(str);
            musicInfo.FullPath = fullPath;
            musicInfo.DurationText = TimeHelper.Second2MinuteSecond(musicInfo.Duration);

            return musicInfo;
        }

        /// <summary>
        /// 获得指定目录下所有的mp3、wav文件
        /// 注意，结果集没有去掉重复添加的项目
        /// </summary>
        /// <param name="rootPath"></param>
        /// <returns></returns>
        public static List<MusicInfo> GetAllAudioFile(string rootPath)
        {
            FileList.Clear();
            DirectoryInfo dir = new DirectoryInfo(rootPath);
            GetAllFiles(dir);
            List<MusicInfo> list = new List<MusicInfo>();
            foreach (FileInfo fi in FileList)
            {
                if (fi.Extension.Equals(".mp3") || fi.Extension.Equals(".wav"))
                {
                    MusicInfo musicInfo = GetMusicInfoByFileFullPath(fi.FullName);
                    list.Add(musicInfo);
                }
            }
            FileList.Clear();
            return list;
        }

        // 获得文件夹下所有的文件
        public static void GetAllFiles(DirectoryInfo dir)
        {
            FileInfo[] fileInfos = dir.GetFiles();
            foreach (FileInfo fi in fileInfos)
            {
                FileList.Add(fi);
            }
            DirectoryInfo[] dirInfos = dir.GetDirectories();
            foreach (DirectoryInfo d in dirInfos)
            {
                GetAllFiles(d);
            }
        }

    }
}
